package com.newegg.research;

import java.io.File;
import java.io.FileWriter;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class ReadDB
{
	static Map<String, StringBuffer> data = new HashMap<String, StringBuffer>();

	private static final String path = "d:/Training_PORTALNEW/";

	public static void main(String[] args) throws Exception
	{
		DBConn conn = new DBConn();
		// ResultSet rs = conn.executeQuery("select \"CatalogDescription\",
		// \"ItemDescription\" from \"AppointedPageInfo4\"");
		ResultSet rs = conn
				.executeQuery("SELECT c.\"CatalogDescription\", i.\"ItemDescription\" FROM \"Items\" as i, \"ItemCatalog\" as c where c.\"CatalogID\" = i.\"CatalogID\"");
		int i = 0;
		while (rs != null && rs.next())
		{
			// System.out.println((i++) + "");
			String c3 = rs.getString(1);
			String name = rs.getString(2);
			insert(name, c3);
		}
		rs.close();
		conn.close();
		write();
	}

	public static void insert(String name, String cat)
	{
		if (name == null || cat == null)
		{
			return;
		}
		name = name.replaceAll("<.*?>", "");
		if (!data.containsKey(cat))
		{
			StringBuffer sb = new StringBuffer(cat);
			sb.append("\n");
			data.put(cat, sb);
		} else
		{
			data.get(cat).append(name).append("\n");
		}
	}

	// 修正非法字符
	public static final String fixName(final String name)
	{
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < name.length(); i++)
		{
			char c = name.charAt(i);
			if (c == '\\' || c == '/')
				c = '、';
			else if (c == '*')
				c = '×';
			else if (c == '?')
				c = '？';

			sb.append(c);
		}
		return sb.toString();
	}

	public static void write() throws Exception
	{
		Set set = data.keySet();
		Iterator<String> it = set.iterator();
		File directory = new File(path);
		if (directory.exists())
		{
			directory.delete();
			directory.mkdirs();
		} else
		{
			directory.mkdirs();
		}
		while (it != null && it.hasNext())
		{
			String cateName = it.next();
			String content = data.get(cateName).toString();

			if (content.length() < 100)
				continue;

			// cateName = URLEncoder.encode(cateName);
			cateName = fixName(cateName);
			// cateName = cateName.replaceAll("\\\\|/", "、");
			if (cateName.length() > 0)
			{
				File newfile = new File(path + cateName);
				if (newfile.exists())
					newfile.delete();
				System.out.println(newfile.getAbsolutePath());
				newfile.createNewFile();
				FileWriter fw = new FileWriter(newfile);
				fw.write(content);
				fw.close();
			}
		}
	}
}
